package com.zw.demo01.common.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Objects;

/**
 * @ClassName: DruidDataSourceUtil
 * @Description TODO
 * @Author: zzw
 * @Date: 2023/3/28 11:34
 * @Version 1.0.0
 */
@Slf4j
public class DruidDataSourceUtil {
    private static Logger logger = LoggerFactory.getLogger(DruidDataSourceUtil.class);

    public static void addOrChangeDataSource(String dbip, String dbport, String dbname, String dbuser, String dbpwd) {

        try {
            DataSourceContextHolder.setDBType("default");

            // 数据库连接key：ip + 端口 + 数据库名
            String key = "db" + dbip + dbport + dbname;

            // 创建动态数据源
            Map<Object, Object> dataSourceMap = DynamicDataSource.getInstance().getDataSourceMap();
            if (!dataSourceMap.containsKey(key + "master") && Objects.nonNull(key)) {
                String url = "jdbc:mysql://" + dbip + ":" + dbport + "/" + dbname + "?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&autoReconnect=true&useSSL=false&testOnBorrow=true&validationQuery=select 1";
                log.info("插入新数据库连接信息为：{}", url);

                DruidDataSource dynamicDataSource = new DruidDataSource();
//                dynamicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
                dynamicDataSource.setUsername(dbuser);
                dynamicDataSource.setUrl(url);
                dynamicDataSource.setPassword(dbpwd);
                dynamicDataSource.setInitialSize(50);
                dynamicDataSource.setMinIdle(5);
                dynamicDataSource.setMaxActive(1000);
                dynamicDataSource.setMaxWait(500); // 如果失败，当前的请求可以返回
                dynamicDataSource.setTimeBetweenEvictionRunsMillis(60000);
                dynamicDataSource.setMinEvictableIdleTimeMillis(300000);
                dynamicDataSource.setValidationQuery("SELECT 1 FROM DUAL");
                dynamicDataSource.setTestWhileIdle(true);
                dynamicDataSource.setTestOnBorrow(false);
                dynamicDataSource.setTestOnReturn(false);
                dynamicDataSource.setPoolPreparedStatements(true);
                dynamicDataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
                dynamicDataSource.setRemoveAbandoned(true);
                dynamicDataSource.setRemoveAbandonedTimeout(180);
                dynamicDataSource.setLogAbandoned(true);
                dynamicDataSource.setConnectionErrorRetryAttempts(0); // 失败后重连的次数
                dynamicDataSource.setBreakAfterAcquireFailure(true); // 请求失败之后中断

                dataSourceMap.put(key + "master", dynamicDataSource);

                DynamicDataSource.getInstance().setTargetDataSources(dataSourceMap);
                // 切换为动态数据源实例
                DataSourceContextHolder.setDBType(key + "master");
            } else {
                // 切换为动态数据源实例
                DataSourceContextHolder.setDBType(key + "master");
            }
        } catch (Exception e) {
            log.error("=====创建据库连接异常：{}", e);
        }
    }
}